package com.ssmeasy.jdgl.utils;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class CookieUtils {


    /**
     * 设置Cookie值
     *
     * @param response
     * @param key
     * @param value
     */
    public static void setCookie(HttpServletResponse response,String key,String value){
        Cookie cookie = new Cookie(key,value);
        cookie.setPath("/");

        response.addCookie(cookie);
    }

    /**
     *
     * 删除Cookie值
     *
     * @param key
     * @param request
     * @param response
     * @return
     */
    public static boolean removeCookie(String key,HttpServletRequest request,HttpServletResponse response){
        Cookie []cookies = request.getCookies();

        if(cookies != null){
            for(Cookie c:cookies){
                if(c.getName().equals(key)){
                    c.setValue(null);
                    c.setMaxAge(0);// 立即销毁cookie
                    c.setPath("/");
                    response.addCookie(c);
                    return true;
                }
            }
        }

        return false;

    }


    /**
     * 获取Cookie值
     *
     * @param request
     * @param key
     * @return
     */
    public static String getCookie(HttpServletRequest request,String key){
        Cookie []cookies = request.getCookies();

        if(cookies != null){
            for(Cookie c:cookies){
                if(c.getName().equals(key)){
                    return c.getValue();
                }
            }
        }
        return null;
    }
}
